<template>
  <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
    <a-row>
      <a-col :span="24" v-for="item in formOptions" :key="item.key">
        <a-form-item :label="item.nameZh" :name="item.key">
          <!-- 下拉 -->
          <a-select
            v-if="item.type === 'select' && item.valid.select.length > 4"
            v-model:value="form[item.key]"
            :placeholder="`请选择${item.nameZh}`"
          >
            <a-select-option v-for="t in item.valid.select" :key="t.value" :value="t.value">
              {{ t.label }}
            </a-select-option>
          </a-select>
          <!-- checkbox -->
          <a-radio-group v-else-if="item.type === 'select' && item.valid.select.length <= 4" v-model:value="form[item.key]" :name="item.key">
            <a-radio v-for="t in item.valid.select" :key="t.value" :value="t.value">{{ t.label }}</a-radio>
          </a-radio-group>
          <!-- 输入 -->
          <a-input v-else-if="item.type === 'string'" v-model:value="form[item.key]" :placeholder="`请输入${item.nameZh}`" />
          <!-- 数值 -->
          <a-input-number v-else-if="item.type === 'int'" v-model:value="form[item.key]" style="width: 100%" :placeholder="`请输入${item.nameZh}`" />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>
<script setup>
  import { reactive, ref } from 'vue';
  import { message } from 'ant-design-vue';

  const rules = {};
  let form = reactive({});
  const formRef = ref();
  let formOptions = ref([]);

  function setOptions(list) {
    for (let item of list) {
      if (item.attribute === 'required') {
        let message = '';
        if (item.type === 'string' || item.type === 'int') {
          message = '请填写';
        } else {
          message = '请选择';
        }
        rules[item.key] = [{ required: true, message: message + item.nameZh }];
      }
    }
    formOptions.value = list;
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 返回值
  function getChildFormData() {
    return form;
  }

  // 编辑的时候的赋值
  function setChildFormData(data) {
    Object.assign(form, data);
  }

  defineExpose({
    setOptions,
    onSubmit,
    getChildFormData,
    setChildFormData,
  });
</script>
